package com.bjpowernode.front.controller;

import com.alibaba.fastjson.JSON;
import com.bjpowernode.api.model.User;
import com.bjpowernode.api.pojo.UserAccountInfoDto;
import com.bjpowernode.common.constants.RedisKey;
import com.bjpowernode.common.enums.RCode;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.common.util.JwtUtil;
import com.bjpowernode.front.service.SmsService;
import com.bjpowernode.front.service.impl.RealnameServiceImpl;
import com.bjpowernode.front.view.RespResult;
import com.bjpowernode.front.vo.RealNameVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "用户功能")
@RequestMapping("/v1/user")
public class UserController extends BaseController {
    @Resource(name = "smsRegisterServiceImpl")
    private SmsService smsRegisterService;

    @Resource(name = "smsLoginServiceImpl")
    private SmsService smsLoginService;

    @Resource
    private RealnameServiceImpl realnameService;
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 用户登录，获取token-jwt
     *
     * @param phone
     * @param pword
     * @param scode
     * @return
     */
    @ApiOperation(value = "用户登录访问token", notes = "用户登录")
    @PostMapping("/login")
    public RespResult login(@RequestParam String phone, @RequestParam String pword, @RequestParam String scode) throws Exception {
        //参数校验
        if (CommonUtil.checkPhone(phone) && pword != null && pword.length() == 32) {
            if (smsLoginService.checkSmsCode(phone, scode)) {
                User user = userService.loginUser(phone, pword);
                if (user != null) {
                    //用户登录成功,生成token
                    HashMap<String, Object> data = new HashMap<>();
                    data.put("uid", user.getId());
                    String jwtToken = jwtUtil.createJwt(data, 120);
                    HashMap<String, Object> userInfo = new HashMap<>();
                    userInfo.put("uid", user.getId());
                    userInfo.put("phone", user.getPhone());
                    userInfo.put("name", user.getName());
                    return RespResult.ok(userInfo, jwtToken);
                } else {
                    return RespResult.fail(RCode.LOGIN_PHONE_PASSWORD_FAIL);
                }
            } else {
                return RespResult.fail(RCode.CHECK_CODE_FAIL);
            }
        } else {
            return RespResult.fail(RCode.REQUEST_PARAM_ERR);
        }
    }

    /**
     * 手机号注册用户
     *
     * @param phone
     * @param pword
     * @param scode
     * @return
     */
    @ApiOperation(value = "手机号注册用户", notes = "手机号注册用户")
    @PostMapping("/register")
    public RespResult userRegister(@RequestParam String phone,
                                   @RequestParam String pword,
                                   @RequestParam String scode) {
        //验证手机号参数
        if (CommonUtil.checkPhone(phone)) {
            //验证密码
            if (pword != null && pword.length() >= 6 && pword.length() <= 32) {
                //短信验证码
                if (smsRegisterService.checkSmsCode(phone, scode)) {
                    //验证码比对成功,可以进行注册
                    int i = userService.userRegister(phone, pword);
                    if (i == 1) {
                        return RespResult.ok();
                    } else if (i == 2) {
                        return RespResult.fail(RCode.PHONE_IS_EXIST);
                    } else {
                        return RespResult.fail();
                    }
                } else {
                    //验证码比对失败
                    return RespResult.fail(RCode.CHECK_CODE_FAIL);
                }
            } else {
                //密码不符合要求
                return RespResult.fail(RCode.CHECK_PASSWORD_FAIL);
            }
        } else {
            //手机号格式不正确
            return RespResult.fail(RCode.PHONE_IS_ILLEGAL);
        }
    }

    /*手机号是否存在*/
    @GetMapping("/phone/exists")
    @ApiOperation(value = "手机号是否注册过", notes = "手机号是否可以注册过")
    public RespResult phoneExists(@RequestParam("phone") String phone) {
        ValueOperations<String, String> phoneCache = stringRedisTemplate.opsForValue();
        //检查请求参数是否符合要求
        if (CommonUtil.checkPhone(phone)) {
            //查询数据库
            //首先查询redis
            String userFromRedis = phoneCache.get(RedisKey.KEY_USER_PHONE + ":" + phone);
            //若redis中没有数据
            if (userFromRedis == null || userFromRedis.equals("")) {
                User user = userService.queryByPhone(phone);
                //如果user中有数据
                if (user != null) {
                    //将查询到的数据放入redis
                    phoneCache.set(RedisKey.KEY_USER_PHONE + ":" + user.getPhone(), JSON.toJSONString(user), 1, TimeUnit.HOURS);
                    return RespResult.fail(RCode.PHONE_IS_EXIST);
                }
            } else {
                return RespResult.fail(RCode.PHONE_IS_EXIST);
            }
        } else {
            return RespResult.fail(RCode.PHONE_IS_ILLEGAL);
        }
        return RespResult.ok();
    }

    @ApiOperation(value = "实名认证", notes = "提供手机号和姓名,身份证号，认证身份证和姓名是否一致")
    @PostMapping("/realname")
    public RespResult userRealName(@RequestBody RealNameVo realNameVo) {
        //检查参数
        if (CommonUtil.checkPhone(realNameVo.getPhone())) {
            if (StringUtils.isNotBlank(realNameVo.getName()) && StringUtils.isNotBlank(realNameVo.getIdCard())) {
                //判断是否已经实名过
                User user = userService.queryByPhone(realNameVo.getPhone());
                //判断user是否有数据
                if (user != null) {
                    if (!StringUtils.isNotBlank(user.getIdCard())) {
                        //短信验证码（先不写）
                        //调用第三方接口
                        boolean realnameResult = realnameService.handleRealname(realNameVo.getPhone(), realNameVo.getName(), realNameVo.getIdCard());
                        if (realnameResult == true) {
                            return RespResult.ok(RCode.REALNAME_IS_SUCCESS);
                        } else {
                            return RespResult.fail(RCode.REALNAME_IS_ILLEGAL);
                        }
                    } else {
                        return RespResult.fail(RCode.REALNAME_IS_EXITS);
                    }
                } else {
                    return RespResult.fail(RCode.UNKOWN);
                }
            } else {
                return RespResult.fail(RCode.REQUEST_PARAM_ERR);
            }
        }
        return RespResult.fail(RCode.REALNAME_IS_ILLEGAL);
    }

    /*用户中心*/
    @ApiOperation(value = "用户中心")
    @GetMapping("/usercenter")
    public RespResult userCenter(@RequestHeader(value = "uid",required = false) Integer uid) {
        HashMap<String, Object> data = new HashMap<>();
        if (uid != null && uid > 0) {
            UserAccountInfoDto userAccountInfoDto = userService.queryUserAllInfo(uid);
            if (userAccountInfoDto != null){
                data.put("name",userAccountInfoDto.getName());
                data.put("phone",userAccountInfoDto.getPhone());
                data.put("headerUrl",userAccountInfoDto.getHeaderImage());
                data.put("money",userAccountInfoDto.getAvailableMoney());
                if (userAccountInfoDto.getLastLoginTime()!= null){
                    data.put("loginTime", DateFormatUtils.format(userAccountInfoDto.getLastLoginTime(),"yyyy-MM-dd HH:mm:ss"));
                }else {
                    data.put("loginTime","-");
                }
                return RespResult.ok(data);
            }
        }
        return RespResult.ok(data);
    }

}
